package com.kingint.web.portal.serve.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kingint.mbg.bas.entity.BasGoods;
import com.kingint.mbg.bas.entity.BasRoom;
import com.kingint.mbg.bas.mapper.BasRoomMapper;
import com.kingint.mbg.dto.rushHouse.RushHouseFrontDetails;
import com.kingint.mbg.dto.rushHouse.RushHouseFrontParam;
import com.kingint.mbg.ser.entity.*;
import com.kingint.mbg.ser.mapper.*;
import com.kingint.mbg.sys.entity.UmsMember;
import com.kingint.mbg.sys.mapper.UmsMemberMapper;
import com.kingint.web.admin.base.service.BasOrderTypeHotelTimeService;
import com.kingint.web.admin.serve.service.SerReceiveWorkMiddleService;
import com.kingint.web.portal.base.service.WorkOrderTypeService;
import com.kingint.web.portal.data.service.DataWorkOrderService;
import com.kingint.web.portal.serve.service.ActivitiCancelService;
import com.kingint.web.portal.serve.service.CheckRoomService;
import com.kingint.web.portal.serve.service.RushHouseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kingint.web.sys.service.UmsAdminService;
import com.kingint.web.util.CharUtil;
import com.kingint.web.util.WorkType;
import com.kingint.web.util.WorkTypeUtil;
import com.kingint.web.util.spring.SpringContextHolder;
import com.kingint.web.vo.CountParam;
import com.kingint.web.vo.RushBean;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 发布赶房表 服务实现类
 * </p>
 *
 * @author wxh
 * @since 2021-01-06
 */
@Service
@Slf4j
public class RushHouseServiceImpl extends ServiceImpl<SerRushHouseMapper, SerRushHouse> implements RushHouseService {


    @Resource
    private UmsAdminService adminService;
    @Resource
    private SerWorkOrderMapper workOrderMapper;
    @Resource
    private SerRushHouseMapper rushHouseMapper;
    @Resource
    private TaskService taskService;
    @Resource
    private ActivitiCancelService activitiCancelService;
    @Resource
    private SerCheckRoomMapper checkRoomMapper;
    @Resource
    private RushBean rushBean;
    @Resource
    private UmsMemberMapper memberMapper;
    @Resource
    private SerGoodsRushHouseLogMapper goodsRushHouseLogMapper;
    @Resource
    private BasRoomMapper roomMapper;
    @Resource
    private SerReceiveWorkMiddleService receiveWorkMiddleService;
    @Resource
    private SerCheckWorkMiddleMapper checkWorkMiddleMapper;
    @Autowired
    public CheckRoomService checkRoomService;
    @Resource
    private WorkOrderTypeService workOrderTypeService;
    @Resource
    private BasOrderTypeHotelTimeService basOrderTypeHotelTimeService;
    @Resource
    private DataWorkOrderService dataWorkOrderService;

    @Override
    public int insertRushHouseInfo(RushHouseFrontParam rushHouseFrontParam) {
        UmsMember currentMember = adminService.getCurrentMember();
        Integer hotelId = currentMember.getHotelId();
        if (StringUtils.isEmpty(hotelId)) {
            log.debug("当前账号未关联酒店id");
            return 0;
        }
        SerWorkOrder workOrder = new SerWorkOrder();
        workOrder.setHotelId(hotelId);//对应酒店
        workOrder.setRoomId(rushHouseFrontParam.getRoomId());//对应房间
        workOrder.setSubmitUserId(currentMember.getId());//提交人员
        workOrder.setCreateTime(new Date());//创建时间
        workOrder.setWorkTypeId(WorkTypeUtil.getWorkTypeIdByName(WorkType.rushHouseName));//对应的工单类型怎么查询出来

        workOrder.setOrderSn(CharUtil.generateOrderSn());//工单号
        int insert = workOrderMapper.insert(workOrder);//插入相关的保修信息

        //同时添加相关的赶房信息
        SerRushHouse rushHouse = new SerRushHouse();
        BeanUtils.copyProperties(rushHouseFrontParam, rushHouse);
        rushHouse.setWorkId(workOrder.getId());//对应总单id
        rushHouse.setCreateTime(new Date());//创建时间
        rushHouse.setCleanStatus(0);//清洁状态未开始
        rushHouseMapper.insert(rushHouse);

        //同时添加相关的总单与接单人中间表ser_receive_work_middle
        SerReceiveWorkMiddle middle = new SerReceiveWorkMiddle();
        middle.setWorkId(workOrder.getId());
        middle.setReceiveUserId(rushHouseFrontParam.getCleanUserId());//清洁人员
        receiveWorkMiddleService.insertReceiveWorkInfo(middle);

        //判断是否为空
        Long checkUserId = rushHouseFrontParam.getCheckUserId();
        if(!StringUtils.isEmpty(checkUserId)){
            //同时添加总表与验收人中间表 ser_check_work_middle
            SerCheckWorkMiddle workMiddle = new SerCheckWorkMiddle();
            workMiddle.setWorkId(workOrder.getId());
            workMiddle.setCreateTime(new Date());
            workMiddle.setCheckUserId(rushHouseFrontParam.getCheckUserId());
            checkWorkMiddleMapper.insert(workMiddle);
        }
        //启动相关的流程实例
        HashMap<String, Object> variables = new HashMap<>();
        variables.put(rushBean.getCreateNameEl(), currentMember.getUsername());//下一步流程执行人
        String businessKey = rushBean.getProcessInstanceKey() + "_" + currentMember.getHotelId() + "_" + workOrder.getId();//业务相关参数
        String processInstanceId = activitiCancelService.startProcess(rushBean.getProcessInstanceKey(), businessKey, variables);
        //更新流程实例id
        workOrder.setProcessInstanceId(processInstanceId);
        workOrder.setOrderStatus(6);
        workOrderMapper.updateById(workOrder);

        //超时统计
        basOrderTypeHotelTimeService.addtim(currentMember.getHotelId(),workOrder.getId(),WorkType.rushHouseName,new Date().getTime());

        //总工单统计
        dataWorkOrderService.addwork(currentMember.getHotelId(), CountParam.RUSHHOUSECOUNT);

        return insert;
    }

    @Override
    public RushHouseFrontDetails getRushHouseInfoById(Integer id) {
        SerRushHouse serRushHouse = rushHouseMapper.selectById(id);
        //查询总单的信息
        Integer workId = serRushHouse.getWorkId();
        SerWorkOrder workOrder = workOrderMapper.selectById(workId);

        //判断当前状态是否是待接单
        Integer orderStatus = workOrder.getOrderStatus();
        if(orderStatus==6){//待确认
            receiveOrderInfo(id);//确认接单
        }
        RushHouseFrontDetails details = new RushHouseFrontDetails();
        BeanUtils.copyProperties(workOrder, details);
        details.setId(id);
        details.setWorkId(workId);

        details.setNowTime(new Date());//当前时间

        Integer roomId = workOrder.getRoomId();
        BasRoom basRoom = roomMapper.selectById(roomId);
        BeanUtils.copyProperties(serRushHouse, details);//拷贝相关的信息
        details.setRoomNum(basRoom.getRoomNum());//房间号
        String arrangeContent = serRushHouse.getArrangeContent();//布草相关信息
        if (!StringUtils.isEmpty(arrangeContent)) {
            List<BasGoods> basGoods = JSONObject.parseArray(arrangeContent, BasGoods.class);
            details.setArrangeContent(basGoods);
        }
        //查询查房，查遗留是否完成
        Integer checkWorkId = serRushHouse.getCheckWorkId();
        if (StringUtils.isEmpty(checkWorkId)) {
            details.setCheckStatus(0);
        } else {//查询对应流程是否完成
            SerWorkOrder serWorkOrder = workOrderMapper.selectById(checkWorkId);
            String processInstanceId = serWorkOrder.getProcessInstanceId();
            //查询当前任务是否完成
            Task task = taskService.createTaskQuery()
                    .processInstanceId(processInstanceId)
                    .singleResult();
            if (StringUtils.isEmpty(task)) {//当前流程已经完成
                details.setCheckStatus(1);
            } else {
                details.setCheckStatus(0);
            }
        }
        return details;
    }

    @Override
    public SerCheckRoom getCheckRoomInfo(Integer id) {
        SerRushHouse serRushHouse = rushHouseMapper.selectById(id);
        Integer checkWorkId = serRushHouse.getCheckWorkId();
        //查询是否存在
        if (StringUtils.isEmpty(checkWorkId)) {
            //不存在就创建对应的查房工单
            SerWorkOrder workOrder = workOrderMapper.selectById(serRushHouse.getWorkId());
            SerCheckRoom checkRoom = new SerCheckRoom();
            checkRoom.setRoomId(workOrder.getRoomId());

            Integer integer = checkRoomService.insertCheckRoomInfo(checkRoom);//创建查房流程，并执行到下一步

            //同时更新赶房中的总单id
            serRushHouse.setCheckWorkId(integer);
            rushHouseMapper.updateById(serRushHouse);
            return checkRoom;
        }
        //不为空 查询查房信息
        QueryWrapper<SerCheckRoom> wrapper = new QueryWrapper<>();
        wrapper.eq("work_id",checkWorkId);
        SerCheckRoom serCheckRoom = checkRoomMapper.selectOne(wrapper);
        return serCheckRoom;
    }

    @Override
    public int finishCheckRoomInfo(SerCheckRoom serCheckRoom) {
        Integer workId = serCheckRoom.getWorkId();
        SerWorkOrder serWorkOrder = workOrderMapper.selectById(workId);
        String processInstanceId = serWorkOrder.getProcessInstanceId();

        //更新查房相关的信息
        serCheckRoom.setCreateTime(new Date());
        QueryWrapper<SerCheckRoom> wrapper = new QueryWrapper<>();
        wrapper.eq("work_id",serCheckRoom.getWorkId());
        int update = checkRoomMapper.update(serCheckRoom, wrapper);
        //查询当前流程实例任务
        Task task = taskService.createTaskQuery()
                .processInstanceId(processInstanceId)
                .singleResult();
        if(!StringUtils.isEmpty(task)){
            taskService.complete(task.getId());
        }
        return update;
    }

    @Override
    public int startRushHouseInfo(Integer status,Integer id) {
        UmsMember currentMember = adminService.getCurrentMember();
        //1.开始赶房，2.完成赶房，3.无需清洁
        if(status==1){//开始赶房
            SerRushHouse house = new SerRushHouse();
            house.setId(id);
            house.setCleanStatus(1);//开始
            house.setStartTime(new Date());//开始时间
          return rushHouseMapper.updateById(house);
        }else if(status==2||status==3){//修改对应状态
            SerRushHouse house = new SerRushHouse();
            house.setId(id);
            house.setCleanStatus(status);//开始
            house.setCompletionTime(new Date());//完成时间
            int i = rushHouseMapper.updateById(house);
            //同时流程实例进行到检查节点
            SerRushHouse rushHouse = rushHouseMapper.selectById(id);
            //判断是不是有检查人
            Long checkUserId = rushHouse.getCheckUserId();
            if(!StringUtils.isEmpty(checkUserId)){//不为空
                UmsMember umsMember = memberMapper.selectById(checkUserId);
                Integer workId = rushHouse.getWorkId();
                SerWorkOrder serWorkOrder = workOrderMapper.selectById(workId);
                String processInstanceId = serWorkOrder.getProcessInstanceId();
                //判断是否有检查人
                Task task = taskService.createTaskQuery()
                        .processInstanceId(processInstanceId)
                        .singleResult();
                if(!StringUtils.isEmpty(task)){
                    HashMap<String, Object> variables = new HashMap<>();
                    variables.put(rushBean.getHaveCheckStatus(),1);//有检查人
                    variables.put(rushBean.getCheckNameEl(), umsMember.getUsername());
                    taskService.setVariables(task.getId(),variables);
                    taskService.complete(task.getId());
                }
            }else{//为空直接完成
                Integer workId = rushHouse.getWorkId();
                SerWorkOrder serWorkOrder = workOrderMapper.selectById(workId);
                String processInstanceId = serWorkOrder.getProcessInstanceId();
                Task task = taskService.createTaskQuery()
                        .processInstanceId(processInstanceId)
                        .singleResult();
                if(!StringUtils.isEmpty(task)){
                    HashMap<String, Object> variables = new HashMap<>();
                    variables.put(rushBean.getHaveCheckStatus(),0);
                    taskService.setVariables(task.getId(),variables);
                    taskService.complete(task.getId());//直接完成
                }
            }
            //同时判断是否超时
            workOrderTypeService.judgeWorkOrderIsTimeOut(currentMember.getId(),rushHouse.getWorkId(),WorkType.rushHouseName);
            basOrderTypeHotelTimeService.deltim(currentMember.getHotelId(),rushHouse.getWorkId(),WorkType.rushHouseName);
            return i;
        }
        return 0;
    }

    @Override
    public List<RushHouseFrontParam> getWaitReceiveList() {
        UmsMember currentMember = adminService.getCurrentMember();
        Integer hotelId = currentMember.getHotelId();
        List<RushHouseFrontParam> rushHouseList = rushHouseMapper.getRushHouseList(hotelId, currentMember.getId(), 6);//待确认
        return rushHouseList;
    }

    @Override
    public Integer receiveOrderInfo(Integer id) {
        SerRushHouse serRushHouse = rushHouseMapper.selectById(id);
        Long cleanUserId = serRushHouse.getCleanUserId();
        UmsMember umsMember = memberMapper.selectById(cleanUserId);
        Integer workId = serRushHouse.getWorkId();
        SerWorkOrder serWorkOrder = workOrderMapper.selectById(workId);
        String processInstanceId = serWorkOrder.getProcessInstanceId();
        Task task = taskService.createTaskQuery()
                .processInstanceId(processInstanceId)
                .singleResult();
        if(!StringUtils.isEmpty(task)){
            //完成当前节点
            HashMap<String, Object> variables = new HashMap<>();
            variables.put(rushBean.getCleanNameEl(), umsMember.getUsername());//下一步流程执行人
            taskService.complete(task.getId(),variables);
            return 1;
        }
        return 0;
    }

    @Override
    public int submitArrangeInfo(RushHouseFrontDetails details) {
        UmsMember currentMember = adminService.getCurrentMember();
        Integer hotelId = currentMember.getHotelId();//对应酒店id
        List<BasGoods> arrangeContent = details.getArrangeContent();
        SerRushHouse house = new SerRushHouse();
        String string = JSONObject.toJSON(arrangeContent).toString();
        house.setId(details.getId());
        house.setArrangeContent(string);
        house.setArrangeStatus(1);
        int i = rushHouseMapper.updateById(house);

        //同时记录布草相关记录
        //先删除对应工单的布草记录
        QueryWrapper<SerGoodsRushHouseLog> wrapper = new QueryWrapper<>();
        wrapper.eq("hotel_id",hotelId)
                .eq("rush_house_id",details.getId());
        goodsRushHouseLogMapper.delete(wrapper);
        for (BasGoods info:arrangeContent) {
            SerGoodsRushHouseLog log = new SerGoodsRushHouseLog();
            log.setBasGoodsId(info.getId());
            log.setCreateTime(new Date());
            log.setGoodsNum(info.getNumber());//数量
            log.setHotelId(hotelId);//酒店id
            log.setRushHouseId(details.getId());
            goodsRushHouseLogMapper.insert(log);
        }
        return i;
    }

    @Override
    public int completeRushHouseInfo(Integer status, Integer id) {
        SerWorkOrder serWorkOrder = workOrderMapper.selectById(id);
        Task task = taskService.createTaskQuery()
                .processInstanceId(serWorkOrder.getProcessInstanceId())
                .singleResult();
        if(!StringUtils.isEmpty(task)){
            Map<String,Object> map=new HashMap<>();
            map.put(rushBean.getRejectStatus(),status);
            taskService.setVariables(task.getId(),map);
            taskService.complete(task.getId());
            return 1;
        }
        return 0;
    }
}
